﻿using System;
using System.Collections.Generic;
using System.Linq;
using Tilver.Data;
namespace Tilver.Test.Data
{
    /// <summary>
    /// 数据路由，在配置节中指定的路由类，需要继承Tilver.Data.DbRouterBase基类
    /// </summary>
    public class DataRouter : DbRouterBase
    {
        private static readonly object _lock = new object();
        private static readonly Dictionary<Type, string> _routerCache = new Dictionary<Type, string>();

        /// <summary>
        /// 路由方法创建数据访问类
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public override DbDataBase RouteDataBase(Type type, object routeData = null)
        {
            if (!_routerCache.ContainsKey(type))
            {
                lock (_lock)
                {
                    if (!_routerCache.ContainsKey(type))
                    {
                        var connectionStringName = "MainDB";
                        //控制不同的类访问不同的数据库
                        if (type.FullName.Contains("Tilver.DAL"))
                        {
                            connectionStringName = "MSSqlDB";//配置文件中定义的数据库访问名称
                        }
                        if (type.FullName.Contains("Tilver.Mysql.DAL"))
                        {
                            connectionStringName = "MySqlDB";
                        }
                        if (type.FullName.Contains("Tilver.Oracle.DAL"))
                        {
                            connectionStringName = "OracleDB";
                        }
                        _routerCache.Add(type, connectionStringName);
                    }
                }
            }
            return  DbDataFactory.Create(_routerCache[type]);
        }
    }
}
